var rootPath = '';//kk.getRootPath();

/* cardDom */
var cardDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
		<div class="row">\
			<form class="form-horizontal" id="cardForm">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="myFile" class="col-sm-2 control-label">图片</label>\
					<div class="col-sm-10">\
						<input type="file" id="myFile" name="file" />\
						<input type="hidden" id="thumb" name="thumb" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="no" class="col-sm-2 control-label">会员卡号<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="no" name="no" placeholder="会员卡号">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="owner_name" class="col-sm-2 control-label">持卡人<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="owner_name" name="owner_name" placeholder="持卡人姓名">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="owner_nickname" class="col-sm-2 control-label">小名</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="owner_nickname" name="owner_nickname" placeholder="小名">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="owner_sex" class="col-sm-2 control-label">性别</label>\
					<div class="col-sm-10">\
						<div id="owner_sex">\
							<input type="radio" name="owner_sex" value="1" data-label="\<i class=\'fa fa-mars\'\>\<\/i\> 男" checked />\
							<input type="radio" name="owner_sex" value="2" data-label="\<i class=\'fa fa-venus\'\>\<\/i\> 女" />\
							<input type="radio" name="owner_sex" value="3" data-label="\<i class=\'fa fa-genderless\'\>\<\/i\> 保密" />\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="owner_birthday" class="col-sm-2 control-label">生日</label>\
					<div class="col-sm-10">\
						<div class="input-group">\
							<input type="text" class="form-control" id="owner_birthday" name="owner_birthday" placeholder="生日">\
							<div class="input-group-addon"><i class="fa fa-calendar"></i></div>\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="owner_tel" class="col-sm-2 control-label">手机<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="tel" class="form-control" id="owner_tel" name="owner_tel" placeholder="手机">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="max_bind_count" class="col-sm-2 control-label">可绑总数</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="max_bind_count" name="max_bind_count" placeholder="可绑总数" value="3">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="max_borrow_count" class="col-sm-2 control-label">可借总数</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="max_borrow_count" name="max_borrow_count" placeholder="可借总数" value="3">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="lv" class="col-sm-2 control-label">借阅等级</label>\
					<div class="col-sm-10">\
						<select class="form-control" id="lv" name="lv">\
							<option value="1" selected="selected">限制会员</option>\
							<option value="2">普通会员</option>\
							<option value="3">高级会员</option>\
							<option value="4">金牌会员</option>\
							<option value="5">钻石会员</option>\
						</select>\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="cur_bind_count" class="col-sm-2 control-label">当前绑定数</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="cur_bind_count" name="cur_bind_count" placeholder="当前绑定数">\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="cur_borrow_count" class="col-sm-2 control-label">当前借阅数</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="cur_borrow_count" name="cur_borrow_count" placeholder="当前借阅数">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="expiry_time" class="col-sm-2 control-label">有效日期</label>\
					<div class="col-sm-10">\
						<div class="input-group">\
							<input type="text" class="form-control" id="expiry_time" name="expiry_time" placeholder="办理日期">\
							<div class="input-group-addon"><i class="fa fa-calendar"></i></div>\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="price" class="col-sm-2 control-label">价格</label>\
					<div class="col-sm-10">\
						<input type="number" class="form-control" id="price" name="price" min="0" value="0" placeholder="价格">\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="update_time" class="col-sm-2 control-label">更新时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="update_time" name="update_time" placeholder="更新时间" />\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="add_time" class="col-sm-2 control-label">添加时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="add_time" name="add_time" placeholder="添加时间" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="description" class="col-sm-2 control-label">简介</label>\
					<div class="col-sm-10">\
						<textarea class="form-control" rows="6" id="description" name="description" placeholder="简介"></textarea>\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
				<div class="foo">\
					<p class="text-muted">1. 图片的尺寸为450*450</p>\
					<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
					<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
					<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
					<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
					<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
				</div>\
			</div>\
			<div class="rm-or-hide">\
				<input type="hidden" name="id" />\
			</div>\
			</form>\
		</div>\
	</div>\
	<div class="box-footer text-center">\
		<button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
		<button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDCardFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Card/Card/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Card/Card/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
		
	$('.main-content').hide();
	$('.main-content').after(cardDom);
	
	var xqu = xqupload('#myFile', {
		uploadUrl			: rootPath + '/Asset/Upload/upload?savePath=card_thumb',
        recvObj				: '#thumb'
    });
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

    	xupload('#myFile', {
    		height: 220,
    		changeHandler: function($this) {
    			$('#thumb').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/cards/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
		$('#owner_birthday').val(kk.timeFormat('yyyy-MM-dd'));
    	$('#expiry_time').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss'));

		$('.rm-or-hide').remove();
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		$('#cardForm').setForm(obj);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.thumb,
    		isDisabled: true
    	});
		$('#owner_birthday').val(kk.timeFormat('yyyy-MM-dd', obj.owner_birthday));
    	$('#expiry_time').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.expiry_time));
    	$('#add_time').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.add_time));

		$('#cardForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');
		
		$('#cardForm').setForm(obj);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.thumb,
    		changeHandler: function($this) {
    			$('#thumb').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/cards/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
		$('#owner_birthday').val(kk.timeFormat('yyyy-MM-dd', obj.owner_birthday));
    	$('#expiry_time').val(kk.timeFormat('yyyy-MM-dd HH:mm:ss', obj.expiry_time));
    	
		$('.rm-or-hide').hide();
	}
	
	xrs("input:radio[name='owner_sex']", {
		xRsLabelClass: 'xrs-label-info',
	});
	
	$('#owner_birthday').datetimepicker({
	    format: 'yyyy-mm-dd',
	    minView: 2,
	    autoclose: true
	});
	$('#expiry_time').datetimepicker({									// 一定是在afterShow的时候初始化
	    format: 'yyyy-mm-dd hh:ii:ss',
	    autoclose: true,
	    todayBtn: true
	});

	var validator = $("#cardForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
	    rules: {
			no: "required",
			owner_name: "required",
			owner_tel: "required",
			email: {
				required: true,
				email: true
			}
	    },
	    messages: {
			no: "请输入会员卡号",
			owner_name: "请输入持卡人姓名",
			owner_tel: "请输入持卡人手机号",
			email: {
		    	required: "请输入Email地址",
		    	minlength: "请输入正确的email地址"
			}
	    }
	});
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		xqu.abort();
		
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
    var url;
    var method;
	var jsonStr = JSON.stringify($('#cardForm').serializeObject());
	var result;
	
	if (operCode == CREATE) {
	 	url = rootPath + '/Card/Card/save';
		method = "POST";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('insertRow', {
				index: 0,
				row: result.obj
			});
	    	
	    	return true;
		}
	} else if (operCode == UPDATE) {
		url = rootPath + '/Card/Card/update?id=' + id;
		method = "PUT";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('updateRow', {
	    		index: index,
				row: result.obj
	    	});
	    	
	    	return true;
		}
	}
	
	return false;
}
